package com.adam.example.search;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import com.adam.example.ElasticsearchClientHolder;
import com.adam.example.types.Nested;

import java.io.IOException;
import java.util.List;

public class SearchNestedExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient client = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchRequest searchRequest = SearchRequest.of(builder -> builder
                        .index("test_nested")
                        .query(queryBuilder -> queryBuilder
                                .nested(nestedQueryBuilder -> nestedQueryBuilder
                                        .path("user").query(queryBuilder1 -> queryBuilder1
                                                .bool(boolQueryBuilder -> boolQueryBuilder
                                                        .must(queryBuilder2 -> queryBuilder2
                                                                .match(matchQueryBuilder -> matchQueryBuilder
                                                                        .field("user.first").query("alice")
                                                                )
                                                        )
                                                        .must(queryBuilder2 -> queryBuilder2
                                                                .match(matchQueryBuilder -> matchQueryBuilder
                                                                        .field("user.last").query("john")
                                                                )
                                                        )
                                                )
                                        )
                                )
                )
        );

        SearchResponse<Nested> searchResponse = client.search(searchRequest, Nested.class);
        HitsMetadata<Nested> hitsMetadata = searchResponse.hits();
        System.out.println("搜索到" + hitsMetadata.total().value() + "条数据");
        List<Hit<Nested>> nestedHitList = hitsMetadata.hits();
        for(int i=0;i<nestedHitList.size();i++) {
            Hit<Nested> nestedHit = nestedHitList.get(i);
            Nested nested = nestedHit.source();
            System.out.println("文档[" + (i+1) + "][评分" + nestedHit.score() + "]:" + nested);
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
